﻿using DryIoc;
using HtmlAgilityPack;
using Loaf.Beans;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace Loaf.Tools
{
    public class HtmlTool
    {
        /// <summary>
        /// 获取搜索结果
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static async Task<List<SearchModel>> GetSearchResult(string filter)
        {
            List<SearchModel> results = new List<SearchModel>();

            try
            {
                //83xs.com
                await Task.Run(() =>
                {
                    var url = "https://www.83xs.com/gdsuisfguigsdugiusiuesu.php?q=" + filter;

                    HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                    HtmlDocument document = new();

                    document.Load(response.GetResponseStream(), Encoding.GetEncoding("gbk"));

                    var xpath = "/html/body/div[3]/div/div/div/div/div[2]";
                    var nodes = document.DocumentNode.SelectNodes(xpath);

                    foreach (var node in nodes)
                    {
                        var bookName = node.ChildNodes[0].FirstChild.InnerText;
                        var bookUrl = "https://www.83xs.com" + node.ChildNodes[0].FirstChild.Attributes["href"].Value;
                        var bookAuthor = node.ChildNodes[2].FirstChild.InnerText;

                        results.Add(new SearchModel
                        {
                            BookName = bookName,
                            BookUrl = bookUrl,
                            BookAuthor = bookAuthor,
                            WebsiteType = WebsiteType.八三小说
                        });
                    }
                });
            }
            catch { }
            try
            {
                //83ks.org
                await Task.Run(() =>
                {
                    var web = new HtmlWeb();
                    var url = "https://www.83ks.org/search/?searchkey=" + filter;
                    var document = web.Load(url);

                    var xpath = "//*[@id=\"wrapper\"]/div[4]/div/table/tbody/tr";
                    var nodes = document.DocumentNode.SelectNodes(xpath);

                    foreach (var node in nodes)
                    {
                        var bookName = node.ChildNodes[3].FirstChild.InnerText;
                        var bookUrl = "https://www.83ks.org" + node.ChildNodes[3].FirstChild.Attributes["href"].Value;
                        var bookAuthor = node.ChildNodes[5].FirstChild.InnerText;

                        results.Add(new SearchModel
                        {
                            BookName = bookName,
                            BookUrl = bookUrl,
                            BookAuthor = bookAuthor,
                            WebsiteType = WebsiteType.八三看书
                        });
                    }
                });
            }
            catch { }

            return results;
        }

        /// <summary>
        /// 获取目录
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static List<BookDictionary> GetHtmlDictionary(string url, WebsiteType type)
        {
            List<BookDictionary> results = new List<BookDictionary>();
            try
            {
                switch (type)
                {
                    case WebsiteType.本地:
                        {
                            results = JsonTool.ReadJson<List<BookDictionary>>(url);
                            break;
                        }
                    case WebsiteType.八三看书:
                        {
                            var web = new HtmlWeb();
                            var document = web.Load(url);
                            var xpath = "//*[@id=\"list\"]/dl/dd";
                            var nodes = document.DocumentNode.SelectNodes(xpath);
                            foreach (var node in nodes)
                            {
                                var titleStr = node.FirstChild.InnerText;
                                var urlStr = "https://www.83ks.org" + node.FirstChild.Attributes["href"].Value;

                                BookDictionary temp = new BookDictionary() { Title = titleStr, Url = urlStr };

                                results.Add(temp);
                            }
                            break;
                        }
                    case WebsiteType.八三小说:
                        {
                            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
                            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                            HtmlDocument document = new();

                            document.Load(response.GetResponseStream(), Encoding.GetEncoding("gbk"));
                            var xpath = "/html/body/div[4]/dl/dd/a";
                            var nodes = document.DocumentNode.SelectNodes(xpath);
                            foreach (var node in nodes)
                            {
                                var titleStr = node.FirstChild.InnerText;
                                var urlStr = "https://www.83xs.com" + node.Attributes["href"].Value;

                                BookDictionary temp = new BookDictionary() { Title = titleStr, Url = urlStr };

                                results.Add(temp);
                            }
                            break;
                        }
                }
            }
            catch { }
            return results;
        }

        /// <summary>
        /// 获取内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetHtmlText(string url, WebsiteType type)
        {
            var result = new StringBuilder("");

            try
            {
                switch (type)
                {
                    case WebsiteType.本地:
                        {
                            return File.ReadAllText(url);
                            break;
                        }
                    case WebsiteType.八三看书:
                        {
                            var web = new HtmlWeb();
                            var document = web.Load(url);
                            var xpath = "//*[@id=\"content\"]/p";
                            var nodes = document.DocumentNode.SelectNodes(xpath);
                            foreach (var node in nodes)
                            {
                                result.AppendLine(node.InnerText);
                            }
                            break;
                        }
                    case WebsiteType.八三小说:
                        {
                            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
                            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                            HtmlDocument document = new();

                            document.Load(response.GetResponseStream(), Encoding.GetEncoding("gbk"));

                            var xpath = "//*[@id=\"content\"]/text()";
                            var nodes = document.DocumentNode.SelectNodes(xpath);

                            foreach (var node in nodes)
                            {
                                if (node.InnerText != "\r")
                                    result.Append(node.InnerText);
                            }

                            result = result.Replace("&nbsp;", "");
                            break;
                        }
                }
            }
            catch { }
            return result.ToString();
        }

    }
}
